package com.software.digitaltwin.tcp;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TCPUtils {
    private static final int MAX_TRY = 1; //最大尝试次数，勿设为0
    private static final String ADDRESS = "192.168.2.1";
    private static final int PORT = 8890;
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    private static TCPConnection connection = null;

    private static boolean getConnection() {
        try {
            connection = new TCPConnection(ADDRESS, PORT);
        } catch (IOException e) {
            System.err.println(DATE_FORMAT.format(new Date()) + "  TCP连接失败");
            return false;
        }
        return true;
    }

    private static boolean checkConnection() {
        int retry = 0;
        while (connection == null || !connection.isConnected()){
            if (retry > MAX_TRY) return false;
            if (getConnection()) {
                return true;
            }
            retry ++;
        }
        return true;
    }

    public static boolean startBelt(byte num, byte speed) {
        if (checkConnection()){
            try {
                connection.startBelt(num, speed);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static boolean stopBelt(byte num) {
        if (checkConnection()){
            try {
                connection.stopBelt(num);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static byte[] getCurrentInfo() {
        if (checkConnection()){
            try {
                return connection.getCurrentInfo();
            } catch (IOException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static boolean push(byte num, byte hold) {
        if (checkConnection()){
            try {
                connection.push(num, hold);
                return true;
            } catch (IOException e) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static byte[] getMachineReport() {
        if (checkConnection()){
            try {
                return connection.getMachineReport();
            } catch (IOException e) {
                return null;
            }
        } else {
            return null;
        }
    }
}
